package com.qy.changemachine.util;

import android.util.Log;

import java.lang.reflect.Method;

/**
 * Utility class to interact with SystemProperties using reflection.
 */
public class SystemPropertiesReflector {
    private static final String TAG = "SystemPropertiesReflector";

    /**
     * Set a system property using reflection.
     *
     * @param key   The property key.
     * @param value The property value.
     */
    public static void set(String key, String value) {
        try {
            // Get the SystemProperties class
            Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");

            // Get the "set" method
            Method setMethod = systemPropertiesClass.getMethod("set", String.class, String.class);

            // Invoke the method statically
            setMethod.invoke(null, key, value);
            Log.i(TAG, "Set system property: " + key + " = " + value);
        } catch (Exception e) {
            Log.e(TAG, "Failed to set system property", e);
        }
    }

    /**
     * Get a system property using reflection.
     *
     * @param key          The property key.
     * @param defaultValue The default value if the property is not found.
     * @return The property value, or the default value if not found.
     */
    public static String get(String key, String defaultValue) {
        try {
            // Get the SystemProperties class
            Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");

            // Get the "get" method
            Method getMethod = systemPropertiesClass.getMethod("get", String.class, String.class);

            // Invoke the method statically and return the result
            return (String) getMethod.invoke(null, key, defaultValue);
        } catch (Exception e) {
            Log.e(TAG, "Failed to get system property", e);
            return defaultValue;
        }
    }
}